package com.voole.security.support;

import java.util.Collection;

import javax.annotation.Resource;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.voole.entity.SysUser;
import com.voole.service.ISysUserService;

/**
 * 根据用户名查询是否存在该用户
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

	@Resource
	private ISysUserService sysuserService;

	public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
		SysUser user = null;
		Collection<GrantedAuthority> grantedAuths = null;
		try {
			//根据名称 查找User类
			user = sysuserService.getSysUserByAccount(account);
			//根据User类 查找它的权限
			grantedAuths = sysuserService.getAuthorities(user);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		//将User的账号、密码、权限放入security的UserDetails中，security自动核对from表单提交的密码
		UserDetails userdetail = new User(user.getAccount(), user.getPassword(), grantedAuths);
		return userdetail;
	}
}